'use strict';

var ISS = {
	contextPath: '',
	resourcePath: '',
	resourceVers: '',
	lang: 'en',
	ifnull: function(value){
		return value == null ? '' : value;
	},
	getPath: function(path){
		if(path.indexOf("/") == 0){
	      path = path.substring(1);
	    }
	    var splitLine = '';
	    if(this.contextPath){
	      var last = this.contextPath.substring(this.contextPath.length -1);
	      if(last != "/"){
	        splitLine = "/";
	      }
	    }
	    var fileTypes = [/.js$/, /.css$/];
	    var isAddVersion = false;
	    for (var index = 0; index < fileTypes.length; index++) {
	    	var regex = fileTypes[index];
	    	if(regex.test(path) && path.indexOf('?') == -1){
	    		isAddVersion = true;
	    	}
	    }
	    // path?v=1231
	    if(isAddVersion){
	    	path = path + '?v=' + this.resourceVers;
	    }
	    //context + '/' + path
		var p = this.contextPath + splitLine + path;
		return p;
	},
	getResPath: function(path){
		var p = this.getPath('/' + path);
		return p;
	},
	now: function(format){
    	if(format == null){
    		format = 'YYYY-MM-DD HH:mm:ss';
    	}
    	return moment().format(format);
    },
	format: function(msg, args){
		if(msg != null && args != null){
			if($.isArray(args)){
				$.each(args, function(i, o){
					msg = msg.replace(/\{\d?\}/, o);
				});
			}else if($.type(args) === "string"){
				msg = msg.replace(/\{\d?\}/, args);
			}
		}
		return msg;
	},
	isEmpty: function(value){
  		return angular.isUndefined(value) 
		  		|| value == null 
		  		|| (angular.isString(value) && value == "") 
		  		|| (angular.isArray(value) && value.length == 0) ;
  	},
  	isNotEmpty: function(value){
  		return !this.isEmpty(value);
  	},
  	uuid: function(){
  		if(ISS._uuid == null){
	  		ISS._uuid = new Date().getTime();
  		}
  		return ISS._uuid++;
  	},
  	extendIsNull: function(dst, src){
    	var _extend = function (d, s){
    		if(!ISS.isEmpty(s)){
	    		angular.forEach(s, function(value, key){
	        		if(ISS.isEmpty(d[key])){
	        			d[key] = value;
	        		}
	        	});
    		}
        	return d;
    	}
    	var _dst = arguments[0];
    	for (var index = 1; index < arguments.length; index++) {
    		_dst = _extend(_dst, arguments[index]);
    	}
    	return _dst;
    },
    getDeviceIcon: function(deviceTypeId){
    	return {
			'List_Gateway_icon':(deviceTypeId == 1),
			'List_TempHumidity_icon':(deviceTypeId == 9),
			'List_Lighting_icon':(deviceTypeId == 24 || deviceTypeId == 306),
			'List_Lightingsensor_icon':(deviceTypeId == 11),
			'List_RubbishCollect_icon' : (deviceTypeId == 309),
			'List_SensorHub_icon' : (deviceTypeId == 310),
			'List_WaterPointSensor_icon' : (deviceTypeId == 311),
			'List_WaterLevelSensor_icon' : (deviceTypeId == 312),
			'List_SewerCoverSensor_icon' : (deviceTypeId == 313)
		}
    },
    newWebsocket: function(url){
		var ws = null;
		var protocol = "ws";
		if(location.protocol.indexOf("https") != -1){
			protocol = "wss";
		}
		var _url = (location.pathname + url).replace('//', '/');
		var url = protocol + "://"+ location.host + _url;
		if ('WebSocket' in window) {
			ws = new WebSocket(url);
		} else if ('MozWebSocket' in window) {
			ws = new MozWebSocket(url);
		} else {
			alert('Your browser Unsupported WebSocket!');
			return;
		}
		var ping = function(){
			setTimeout(function(){
				if(ws != null && ws.readyState != ws.CLOSED){
					ws.send('--ping--');
					ping();
				}
			}, 30000);
		}
		ping();
		return ws;
	},
    reg: {
		"email": /^(([A-Za-z0-9]+([_\.-]*[A-Za-z0-9]+)*)@([A-Za-z0-9\.-]+)\.([a-z]{2,3})){0,128}$/,
		"planInterval": /^\d{1,4}$/,
		"ip": /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])(\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])){3}$/,
		"port": /^([0-9]|[1-9]\d|[1-9]\d{2}|[1-9]\d{3}|[1-5]\d{4}|6[0-4]\d{3}|65[0-4]\d{2}|655[0-2]\d|6553[0-5])$/,
		"path": /^[a-zA-Z]:[\\/]((?! )(?![^\\/]*\s+[\\/])[\w -]+[\\/])*(?! )(?![^.]+\s+\.)$/,
		"ftpPath": /^(\/(\w+\/?)+)$/,
		"account": /^([0-9a-zA-Z_])+$/,	//账号
		"phone":/^[\+\d-]+$/,	//电话
		"tel":/^([0-9-])+$/,
		"fox":/^([0-9-]){0,16}$/,
		"integer":/^([1-9]+)([0-9]*)$|^(0)$/,	//正整数
		"int":/^([1-9]+)([0-9]*)$|^(0)$/,	//正整数
		"pmint":/^-?\d+$/,		//整数(正、负、0)
		"test":/^[-]?[0-9]{1}[0-9]+$/,
		"double":/^-?\d+(\.\d+)?$/,		//数字(负数，正数,小数)
		"alphanumeric":/^\w+$/i,	//数字、字母、下划线
		"cbemsName":/^([a-zA-Z0-9_\-\u4e00-\u9fa5])+$/,
		"cbemsChartName":/^([a-zA-Z0-9_\-\u4e00-\u9fa5-\u0020])+$/,
		"date": function(value, format){//校验日期
			if(format !== undefined){
				format = moment.fn.toMomentFormatString(format);
			}
			var _moment = moment(value, format);
			var valid = _moment.isValid();
			if(valid){
				return _moment.format(format) == value; 
			}
			return false;
		},
		"time": function(value, format){
			if(ISS.isEmpty(format)){
				format = 'HH:mm:ss';
			}
			var _moment = moment(value, format);
			var valid = _moment.isValid();
			//校验是否为时间
			if(valid){
				return _moment.format(format) == value; 
			}
			return false;
		},
		"checkNumber": function(value, intMax, decMax){
			if(value == undefined || value == null || value == ""){
				return true;
			}
			value = value + "";
			if(value.indexOf('-') == 0){
				value = value.substring(1, value.length);
			}
			if(/^([\d]+)([.]?)([\d]*)$/.test(value)){
				if(intMax != undefined || decMax != undefined){
					var integerLen = 0, decimalLen = 0;
					if(intMax != undefined && intMax != null){
						integerLen = intMax;
					}
					if(decMax != undefined && decMax != null){
						decimalLen = decMax;
					}
					//拼接正则表达式
					var pattern = ["/"];
					var p = "^([\\d]{1," + integerLen + "})";//只有整数
					if(decimalLen == 0){
						p += "$";
					}else{
						p = p + "$|" + p + "([.]{1})([\\d]{1," + decimalLen + "})$";//有小数
					}
					pattern.push(p);
					pattern.push("/");
					
					var regexp = eval(pattern.join(""));
					return regexp.test(value);
				}
				return true;
			}
			return false;
		}
	},
	settings: {
		themeID: 1,
		navbarHeaderColor: 'bg-primary',
		navbarCollapseColor: 'bg-primary',
		asideColor: 'bg-white-only',
		headerFixed: false,
		asideFixed: true,
		asideFolded: false,
		asideDock: false,
		container: false
	},
	mapType:'amap',
	getMapPath:function(){
		var loads = [];
		if(ISS.mapType == 'google'){
           loads.push(ISS.getResPath('js/app/map/load-gmap.js'));
           loads.push(ISS.getResPath('js/app/map/ui-gmap.js'));
        }else if(ISS.mapType == 'amap'){
           loads.push(ISS.getResPath('js/app/map/load-amap.js'));
           loads.push(ISS.getResPath('js/app/map/ui-amap.js'));
        }
		loads.push(ISS.getResPath('js/controllers/latLngSelectCtrl.js'));
        return loads;
	},
	loadMap:function(){
		if(ISS.mapType == 'google'){
		    return loadGoogleMaps(null, 'AIzaSyCxZocCRhsP15hp46xyup5BtbJ8lb5lRsI', (ISS.lang=='zh' ? 'zh-CN' : 'en'));
	    }else if(ISS.mapType == 'amap'){
            return load_AMap(1.3, '3189090ae367fff6ee4262a882b27cd6');
	    }
	},
	/**
	 * 公共字符串转json方法，转换失败返回null
	 * @param data 字符串
	 * @returns json格式字符串，转换失败返回null
	 */
	toJsonData:function (data){
		var jsonData = null;
		if(typeof(data) == "string"){
			try
			{
				jsonData = eval('('+data+')');
			}catch(e)
			{
				
			}
		}
		
		return jsonData;
	}
}




